﻿using MSTutHelloWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace MSTutHelloWebAPI.Models
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[]
        {
            new Product{Id=1,Name="Tomato Soup",Category="Groceries",Price=1},
            new Product{Id=2,Name="Yo-yo",Category="Toys",Price=3.75M},
            new Product{Id=3,Name="Hammer",Category="Hardware",Price=16.99M}
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public string GetTATOutput(string input)
        {
            if (input.Length==0)
            {
                return "INVALID INPUT";
            }
            string result = "";
            TextAnalytics ta = null;
            PoolManager s = PoolManager.Instance;
            try
            {
                ta = (TextAnalytics)s.ReleaseObject();
                //Comment out the two lines below so that 'result' will be JSON formatted string
                ObjResult tempObj = SplitResult(ta.Go(input));
                result = new JavaScriptSerializer().Serialize(tempObj);

                //Comment out the two lines below so that 'result' will be HTML formatted string, it can be displayed in <p> tag
                //ObjResult tempObj = SplitResult(ta.Go(input));
                //result = "LTA: " + tempObj.LTA + "%<br />NEA: " + tempObj.NEA + "%<br />PUB: " + tempObj.PUB + "%<br /><br />This Case most likely belongs to:  " + tempObj.RecomAgency;
            }
            catch (Exception ex)
            {
                result = "Unable to execute python script. " + ex.Message;
            }
            finally
            {
                if (ta != null) { s.AddObject(ta); }
            }
            return result;
        }

        private ObjResult SplitResult(string tempResult)
        {
            string[] StrSplit = Regex.Split(tempResult, "% \r\r\n");

            ObjResult tempObj = new ObjResult();
            tempObj.LTA = StrSplit[0].Split(':')[1];
            tempObj.NEA = StrSplit[1].Split(':')[1];
            tempObj.PUB = StrSplit[2].Split(':')[1];
            tempObj.RecomAgency = StrSplit[3].Split(':')[1].ToUpper().Replace("\r\n","");
            return tempObj;
        }
    }
}
